import React, { useEffect, useRef } from 'react'
import { Col } from 'antd'
import * as echarts from 'echarts'
import { getAveScore } from '../lib/publicMethod'
import VCData from '../interface/VCData'

interface ITeaToScore {
  tea: string,
  aveScore: number
}
interface ITeaToList {
  [key: string]: VCData[]
}
interface IProps {
  data: VCData[]
}
export default function Ranking(props: IProps) {
  const data = props.data
  const highEl = useRef<HTMLDivElement | null>(null)
  const lowEl = useRef<HTMLDivElement | null>(null)
  const highEc = useRef<echarts.ECharts | null>(null)
  const lowEc = useRef<echarts.ECharts | null>(null)
  useEffect(() => {
    highEc.current = echarts.init(highEl.current as HTMLDivElement)
    lowEc.current = echarts.init(lowEl.current as HTMLDivElement)
  }, [])
  useEffect(() => {
    //平均得分最高的十位讲师、最低五位讲师
    const teaToList: ITeaToList = {}
    for (let i = 0; i < data.length; i++) {
      if (teaToList[data[i]['姓名']]) {
        teaToList[data[i]['姓名']].push(data[i])
      } else {
        teaToList[data[i]['姓名']] = [data[i]]
      }
    }
    const teaToAveScore: ITeaToScore[] = []
    Object.keys(teaToList).forEach(item => {
      teaToAveScore.push({
        tea: item,
        aveScore: getAveScore(teaToList[item as keyof typeof teaToList])
      })
    })
    teaToAveScore.sort((a, b) => a.aveScore - b.aveScore)
    const highX: string[] = []
    const highY: number[] = []
    const lowX: string[] = []
    const lowY: number[] = []
    teaToAveScore.slice(0, 5).forEach(item => {
      lowX.push(item.tea)
      lowY.push(item.aveScore)
    })
    teaToAveScore.slice(-10).reverse().forEach(item => {
      highX.push(item.tea)
      highY.push(item.aveScore)
    });
    //得分最高前10名
    (highEc.current as echarts.ECharts).setOption({
      title: {
        text: '得分最高前10名'
      },
      legend: {
        data: ['总分平均值']
      },
      xAxis: {
        data: highX
      },
      yAxis: {},
      series: [{
        name: '总分平均值',
        type: 'bar',
        data: highY,
        label: {
          show: true
        },
        itemStyle: {
          color: 'rgb(240,124,130)'
        }
      }]
    });
    //得分最低前5名
    (lowEc.current as echarts.ECharts).setOption({
      title: {
        text: '得分最低前5名'
      },
      legend: {
        data: ['总分平均值']
      },
      xAxis: {
        data: lowX
      },
      yAxis: {},
      series: [{
        name: '总分平均值',
        type: 'bar',
        data: lowY,
        label: {
          show: true
        },
        itemStyle: {
          color: 'rgb(56,33,41)'
        }
      }]
    });
  }, [data])
  return (
    <>
      <Col span={12}>
        <div className="show" ref={highEl}></div>
      </Col>
      <Col span={12}>
        <div className="show" ref={lowEl}></div>
      </Col>
    </>
  )
}
